<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生选课系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ddd;
        }
        .user-info {
            display: flex;
            align-items: center;
        }
        .logout-btn {
            margin-left: 15px;
            padding: 5px 10px;
            background-color: #f44336;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .container {
            display: flex;
            gap: 20px;
        }
        .section {
            flex: 1;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
        }
        .course-item {
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #eee;
            border-radius: 4px;
            background-color: #f9f9f9;
        }
        .course-item:hover {
            background-color: #f0f0f0;
        }
        .action-btn {
            padding: 5px 10px;
            margin-top: 10px;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
        }
        .action-btn.drop {
            background-color: #f44336;
        }
        h2 {
            color: #333;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }
        .message {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
        }
        .success {
            background-color: #dff0d8;
            color: #3c763d;
        }
        .error {
            background-color: #f2dede;
            color: #a94442;
        }
        .action-btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>学生选课系统</h1>
        <div class="user-info">
            <span id="user-name">加载中...</span>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
    </div>
    
    <div id="message-box"></div>
    
    <div class="container">
        <div class="section">
            <h2>可选课程列表</h2>
            <div id="available-courses"></div>
        </div>
        
        <div class="section">
            <h2>已选课程</h2>
            <div id="selected-courses"></div>
        </div>
    </div>
    
    <script>
        // 获取当前登录的学生信息
        const studentJson = localStorage.getItem('student');
        let student = null;
        
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            if (!studentJson) {
                // 未登录，跳转到登录页
                window.location.href = '/login.html';
                return;
            }
            
            student = JSON.parse(studentJson);
            document.getElementById('user-name').textContent = `${student.username} (学号: ${student.studentNo})`;
            
            loadAllCourses();
            loadMyCourses();
        });
        
        // 登出
        function logout() {
            fetch('/api/auth/logout', {
                method: 'POST'
            })
            .then(() => {
                localStorage.removeItem('student');
                window.location.href = '/login.html';
            })
            .catch(error => {
                console.error('退出登录失败:', error);
                // 即使API调用失败，也清除本地存储并跳转
                localStorage.removeItem('student');
                window.location.href = '/login.html';
            });
        }
        
        // 显示消息
        function showMessage(message, isError = false) {
            const messageBox = document.getElementById('message-box');
            messageBox.innerHTML = `<div class="message ${isError ? 'error' : 'success'}">${message}</div>`;
            
            // 3秒后自动清除消息
            setTimeout(() => {
                messageBox.innerHTML = '';
            }, 3000);
        }
        
        // 加载所有课程
        function loadAllCourses() {
            return fetch('/api/courses')
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        displayAvailableCourses(result.result);
                    } else {
                        showMessage('获取课程列表失败: ' + result.message, true);
                    }
                    return result;
                })
                .catch(error => {
                    showMessage('获取课程列表出错: ' + error.message, true);
                    throw error;
                });
        }
        
        // 加载当前学生已选课程
        function loadMyCourses() {
            return fetch(`/api/student-courses/student/${student.id}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        displaySelectedCourses(result.result);
                    } else {
                        showMessage('获取已选课程失败: ' + result.message, true);
                    }
                    return result;
                })
                .catch(error => {
                    showMessage('获取已选课程出错: ' + error.message, true);
                    throw error;
                });
        }
        
        // 选课
        function selectCourse(courseId) {
            const params = new URLSearchParams();
            params.append('studentId', student.id);
            params.append('courseId', courseId);
            
            fetch(`/api/student-courses/enroll?${params.toString()}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    showMessage('选课成功');
                    // 先加载已选课程，再加载所有课程
                    loadMyCourses().then(() => {
                        loadAllCourses();
                    });
                } else {
                    showMessage('选课失败: ' + result.message, true);
                    // 刷新课程列表，确保显示最新状态
                    loadAllCourses();
                }
            })
            .catch(error => {
                showMessage('选课操作出错: ' + error.message, true);
                // 出错也刷新，确保UI状态正确
                loadAllCourses();
            });
        }
        
        // 退课
        function dropCourse(courseId) {
            const params = new URLSearchParams();
            params.append('studentId', student.id);
            params.append('courseId', courseId);
            
            fetch(`/api/student-courses/drop?${params.toString()}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    showMessage('退课成功');
                    // 先加载已选课程，再加载所有课程
                    loadMyCourses().then(() => {
                        loadAllCourses();
                    });
                } else {
                    showMessage('退课失败: ' + result.message, true);
                    // 失败也刷新，确保UI状态正确
                    loadMyCourses();
                }
            })
            .catch(error => {
                showMessage('退课操作出错: ' + error.message, true);
                // 出错也刷新，确保UI状态正确
                loadMyCourses();
            });
        }
        
        // 显示可选课程
        function displayAvailableCourses(courses) {
            const container = document.getElementById('available-courses');
            container.innerHTML = '';
            
            if (!courses || courses.length === 0) {
                container.innerHTML = '<p>没有可选课程</p>';
                return;
            }
            
            courses.forEach(course => {
                // 检查学生是否已选该课程
                fetch(`/api/student-courses/check?studentId=${student.id}&courseId=${course.id}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            const hasSelected = result.result;
                            
                            const courseElement = document.createElement('div');
                            courseElement.className = 'course-item';
                            courseElement.innerHTML = `
                                <h3>${course.courseName} (${course.courseCode})</h3>
                                <p>已选/容量: ${course.currentEnrollment}/${course.maxCapacity}</p>
                                <button class="action-btn" onclick="selectCourse(${course.id})" 
                                    ${hasSelected || course.currentEnrollment >= course.maxCapacity ? 'disabled' : ''}>
                                    ${hasSelected ? '已选' : '选课'}
                                </button>
                            `;
                            container.appendChild(courseElement);
                        }
                    });
            });
        }
        
        // 显示已选课程
        function displaySelectedCourses(courses) {
            const container = document.getElementById('selected-courses');
            container.innerHTML = '';
            
            if (!courses || courses.length === 0) {
                container.innerHTML = '<p>尚未选择任何课程</p>';
                return;
            }
            
            courses.forEach(course => {
                const courseElement = document.createElement('div');
                courseElement.className = 'course-item';
                courseElement.innerHTML = `
                    <h3>${course.courseName} (${course.courseCode})</h3>
                    <p>已选/容量: ${course.currentEnrollment}/${course.maxCapacity}</p>
                    <button class="action-btn drop" onclick="dropCourse(${course.id})">退课</button>
                `;
                container.appendChild(courseElement);
            });
        }
    </script>
</body>
</html> 